var stompClient = null;
function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled",!connected);
    if(connected){
        $("#greetings").show();
    }else {
        $("#greetings").hide();
    }
    $("#greetings").html("");
}
function connect() {
    var socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({},function (frame) {
        setConnected(true);
        stompClient.subscribe('/user/queue/chat',function (greeting) {
            showGreeting(JSON.parse(greeting.body));
        });
    });
}
function disconnect() {
    if(stompClient != null){
        stompClient.disconnect();
    }
    setConnected(false);
}
function sendName(content) {
    stompClient.send("/app/chat",{},
        JSON.stringify({'to':$("#to").val(),'content':content}));
}
function showGreeting(message) {
    $("#greetings").append("<div>"+message.from+":"+message.content+"</div>");
}

$(function () {
    $("#send").click(function () {
        var content = $("#content").val();
        sendName(content);
    });
    $("#connect").click(function () {
        connect();
    });
    $("#disconnect").click(function () {
        disconnect();
    });
});